package com.example.dllo.baidumusic.service;
/*
                   _ooOoo_
                  o8888888o
                  88" . "88
                  (| -_- |)
                  O\  =  /O
               ____/`---'\____
             .'  \\|     |//  `.
            /  \\|||  :  |||//  \
           /  _||||| -:- |||||-  \
           |   | \\\  -  /// |   |
           | \_|  ''\---/''  |   |
           \  .-\__  `-`  ___/-. /
         ___`. .'  /--.--\  `. . __
      ."" '<  `.___\_<|>_/___.'  >'"".
     | | :  `- \`.;`\ _ /`;.`/ - ` : | |
     \  \ `-.   \_ __\ /__ _/   .-` /  /
======`-.____`-.___\_____/___.-`____.-'======
                   `=---='
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
         佛祖保佑       永无BUG
*/

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.MediaPlayer;
import android.os.Binder;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v4.app.NotificationManagerCompat;
import android.support.v7.app.NotificationCompat;
import android.widget.RemoteViews;
import android.widget.Toast;

import com.example.dllo.baidumusic.R;
import com.example.dllo.baidumusic.bean.MusicBean;
import com.example.dllo.baidumusic.events.AskState;
import com.example.dllo.baidumusic.events.MusicListEvent;
import com.example.dllo.baidumusic.events.NextEvent;
import com.example.dllo.baidumusic.events.OnlyEvent;
import com.example.dllo.baidumusic.events.PreviousEvent;
import com.example.dllo.baidumusic.events.SingInfoEvent;
import com.example.dllo.baidumusic.bean.MusicBeanListBean;
import com.example.dllo.baidumusic.nettool.NetTool;
import com.example.dllo.baidumusic.noitify.PlayerNotification;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.IOException;
import java.util.List;
import java.util.Random;

/**
 * Created by dllo on 16/8/20.
 */
public class PlayService extends Service implements MediaPlayer.OnCompletionListener {
    public static final String KEY_PRORESS = "progress";
    public static final String ACTION_PROGRESS = "com.com.xxx";
    private MediaPlayer mediaPlayer;
    private int musicPos;//当前播放的位置
    private List<MusicBean> musicBeanList;//歌曲列表
    private NetTool netTool;
    private Intent progressIntent;
    private NotificationManager manager;
    private RemoteViews remoteViews;
    private int i = 0;
    private NotificationManagerCompat notificationManagerCompat;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return new MusicBinder();
    }


    @Override
    public void onCreate() {
        super.onCreate();
        progressIntent = new Intent(ACTION_PROGRESS);
        EventBus.getDefault().register(this);

        mediaPlayer = new MediaPlayer();
        mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                showNotifycation();
                /*
                    发送歌曲信息 及当前位置 postion
                 */
                MusicBeanListBean musicBeanListBean = new MusicBeanListBean(musicBeanList, musicPos);
                EventBus.getDefault().post(musicBeanListBean);
                mp.start();


            }
        });

        // 注册广播
        IntentFilter filter = new IntentFilter();
        filter.addAction("com.baidumusic.notification.back");
        filter.addAction("com.baidumusic.notification.next");
        filter.addAction("com.baidumusic.notification.state");
        filter.addAction("com.baidumusic.notification.clear");
        registerReceiver(receiver, filter);


        netTool = new NetTool(this);
        //进度条
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    sleep();
                    if (!mediaPlayer.isPlaying()) {
                        continue;
                    }
                    int seek = mediaPlayer.getCurrentPosition();
                    int percent = (int) (seek * 100f / mediaPlayer.getDuration());
                    progressIntent.putExtra(KEY_PRORESS, percent);
                    sendBroadcast(progressIntent);

                }
            }


        }).start();
    }

    private void sleep() {
        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    //通知


    private void showNotifycation() {
        PlayerNotification playerNotification = new PlayerNotification(this);
        playerNotification.showNotify(musicBeanList.get(musicPos).getSingerName(), musicBeanList.get(musicPos).getMusicName());

//        startForeground(1, notification);//让服务和notification和服务绑定在一起,成为前台服务,Notification和Serviec的存活时间就会一致

    }

    @Override
    public void onDestroy() {
        EventBus.getDefault().register(this);
        netTool.onDestroy();
        super.onDestroy();
    }


    private void pause() {

        if (mediaPlayer.isPlaying() && mediaPlayer != null) {
            mediaPlayer.pause();
        } else {
            mediaPlayer.start();
        }
    }

    //下一首
    private void next() {
        if (musicPos + 1 < musicBeanList.size()) {
            musicPos++;
            playMusic();
        } else {
            Toast.makeText(this, "没有下一曲啦~ ~", Toast.LENGTH_SHORT).show();
        }
    }

    //上一首
    private void previous() {
        if ((musicPos - 1) >= 0) {
            musicPos--;
            playMusic();
        } else {
            Toast.makeText(this, "这已经是第一首了", Toast.LENGTH_SHORT).show();
        }
    }

    private void onlyplay() {
        mediaPlayer.setLooping(true);
        playMusic();

    }


    @Subscribe
    public void next(NextEvent nextEvent) {
        next();
        singinfo();
    }

    @Subscribe
    public void previousEv(PreviousEvent previousEvent) {
        previous();
        singinfo();
    }

    @Subscribe
    public void only(OnlyEvent onlyEvent) {
        onlyplay();

    }

    //歌曲相关信息
    public void singinfo() {
        MusicBeanListBean musicBeanListBean = new MusicBeanListBean(musicBeanList, musicPos);
        EventBus.getDefault().post(musicBeanListBean);
    }

    @Subscribe(threadMode = ThreadMode.BACKGROUND)
    public void sendMusicInFo(SingInfoEvent singInfoEvent) {
        MusicBean musicBean = musicBeanList.get(musicPos);
        EventBus.getDefault().post(musicBean);
    }

    @Subscribe
    public void setMusicBeanList(MusicListEvent musicListEvent) {
        this.musicBeanList = musicListEvent.getMusicBeanList();
        this.musicPos = musicListEvent.getPostion();
        EventBus.getDefault().post(this.musicBeanList);
        playMusic();
    }

    public void playMusic() {
        if (mediaPlayer.isPlaying()) {
            mediaPlayer.stop();
        }
        mediaPlayer.reset();//重置播放器

        try {

            mediaPlayer.setDataSource(musicBeanList.get(musicPos).getUrl());
            mediaPlayer.prepare();
            mediaPlayer.start();
//            mediaPlayer.setLooping(true);
            mediaPlayer.setOnCompletionListener(this);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //播放/暂停
    @Subscribe
    public void state(AskState askState) {
        pause();
    }

//    public class agorithm {
//
//        public void shuffle(String[] musicUrl) {
//            int shuffle_key;
//            String temp;
//            Random rand = new Random();
//            for (int i = 0; i < musicUrl.length; i++) {
//                shuffle_key = rand.nextInt(musicUrl.length - 1);
//                temp = musicUrl[i];
//                musicUrl[i] = musicUrl[shuffle_key];
//                musicUrl[shuffle_key] = temp;
//            }
//        }
//    }

    //随机
    //    private static Random r;
//    public void shuffle(List<MusicBeanListBean> list){
//
//        Random rnd = r;
//        if (rnd == null)
//            r = rnd = new Random();
//        shuffle(list, rnd);
//    }
//    public static void shuffle(List<MusicBeanListBean> list, Random rnd) {
//        int size = list.size();
//        if (size < ; || list instanceof RandomAccess) {
//            for (int i=size; i>1; i--)
//                swap(list, i-1, rnd.nextInt(i));
//        } else {
//            Object arr[] = list.toArray();
//
//            // Shuffle array
//            for (int i=size; i>1; i--)
//                swap(arr, i-1, rnd.nextInt(i));
//
//            // Dump array back into list
//            ListIterator it = list.listIterator();
//            for (int i=0; i<arr.length; i++) {
//                it.next();
//                it.set(arr[i]);
//            }
//        }
//    }
//循环
//    private void cycleRepeat() {
//            if (mediaPlayer == null) {
//                    return;
//                }
//            try {
//                    int mode = mediaPlayer.getRepeatMode();
//                    if (mode == MediaPlaybackService.REPEAT_NONE) {
//                    mService.setRepeatMode(MediaPlaybackService.REPEAT_ALL);
//                    showToast(R.string.repeat_all_notif);
//                } else if (mode == MediaPlaybackService.REPEAT_ALL) {
//                    mService.setRepeatMode(MediaPlaybackService.REPEAT_CURRENT);
//                    if (mService.getShuffleMode() != MediaPlaybackService.SHUFFLE_NONE) {
//                            mService.setShuffleMode(MediaPlaybackService.SHUFFLE_NONE);
//                            setShuffleButtonImage();
//                        }
//                    showToast(R.string.repeat_current_notif);
//                } else {
//                    mService.setRepeatMode(MediaPlaybackService.REPEAT_NONE);
//                    showToast(R.string.repeat_off_notif);
//                }
//                    setRepeatButtonImage();
//                } catch (RemoteException ex) {
//                }
//
//            }
    private Notification createNotifycation() {
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
        notificationManagerCompat = NotificationManagerCompat.from(this);
        RemoteViews views = new RemoteViews(getPackageName(), R.layout.remtoe_notifycation);
        views.setTextViewText(R.id.notify_singername, musicBeanList.get(musicPos).getSingerName());
        views.setTextViewText(R.id.notify_singname, musicBeanList.get(musicPos).getMusicName());
        builder.setContent(views);
        return builder.build();

    }


    //通知点击事件
    public PendingIntent getPendingIntent() {
        Intent intent = new Intent("baidu.intent");
        PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 111, intent, PendingIntent.FLAG_CANCEL_CURRENT);

        return pendingIntent;
    }

    @Override
    public void onCompletion(MediaPlayer mp) {
        if (++musicPos >= musicBeanList.size()) {
            Toast.makeText(this, "已经是最后一曲啦", Toast.LENGTH_SHORT).show();
            musicPos--;
        } else {
            playMusic();
        }
    }//自动播放下一首


    private void seekToo(int progerss) {
        int duration = mediaPlayer.getDuration();
        int seek = (int) (progerss / 100f * duration);
        mediaPlayer.seekTo(seek);

    }

    //seebar
    public class MusicBinder extends Binder {
        public int getMusicDeration() {
            int rtn = 0;
            if (mediaPlayer != null) {
                rtn = mediaPlayer.getDuration();//时长
            }
            return rtn;
        }

        public int PlayMusicAcyivity() {
            int rtn = 0;
            if (mediaPlayer != null) {
                rtn = mediaPlayer.getCurrentPosition();//播放时长
            }
            return rtn;
        }

        public void seekTo(int progress) {

            seekToo(progress);
        }
    }

    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            switch (action) {
                case "com.baidumusic.notification.back":
                    previous();
                    break;
                case "com.baidumusic.notification.next":
                    next();
                    break;
                case "com.baidumusic.notification.state":
                    pause();
                    break;
                case " com.baidumusic.notification.clear":

                    break;
            }
        }
    };


}
